package com.smart.community.region.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.region.dto.BatchCreateFeeStandardDTO;
import com.smart.community.region.entity.ShopFeeStandard;
import com.smart.community.region.mapper.ShopFeeStandardMapper;
import com.smart.community.region.service.IShopFeeStandardService;
import com.smart.community.region.service.IShopService;
import com.smart.community.region.entity.Shop;
import com.smart.community.region.vo.ShopFeeStandardVO;

import io.seata.spring.annotation.GlobalTransactional;

import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.commons.cache.DataScopeInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺费用标准Service实现类
 * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
 * 遵循《系统状态枚举权威标准声明.md》状态枚举规范
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2025-01-30
 */
@Slf4j
@Service
public class ShopFeeStandardServiceImpl extends ServiceImpl<ShopFeeStandardMapper, ShopFeeStandard> 
        implements IShopFeeStandardService {
    
    
    @Autowired
    private IShopService shopService;
    
    @Autowired
    private DataScopeFeign dataScopeFeign;
    
    /**
     * 批量新增费用标准
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     * 遵循《系统状态枚举权威标准声明.md》状态枚举规范
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"feeStandard:page", "feeStandard:list", "feeStandard:detail"}, allEntries = true)
    public List<Long> batchCreateFeeStandard(BatchCreateFeeStandardDTO batchCreateDTO) throws Exception {
        log.info("开始批量新增费用标准，店铺数量: {}, 费用类型: {}", 
                batchCreateDTO.getShopIds().size(), batchCreateDTO.getFeeType());
        
        try {
            // 参数验证
            validateBatchCreateParams(batchCreateDTO);
            
            // 数据权限验证
            validateDataPermission(batchCreateDTO.getShopIds());
            
            // 检查冲突
            checkConflicts(batchCreateDTO);
            
            // 构建费用标准实体列表
            List<ShopFeeStandard> feeStandards = buildFeeStandards(batchCreateDTO);
            
            // 批量保存
            boolean saveResult = saveBatch(feeStandards);
            if (!saveResult) {
                throw new RuntimeException("批量保存费用标准失败");
            }
            
            // 返回创建的ID列表
            List<Long> createdIds = feeStandards.stream()
                    .map(ShopFeeStandard::getId)
                    .collect(Collectors.toList());
            
            log.info("批量新增费用标准成功，创建数量: {}", createdIds.size());
            return createdIds;
            
        } catch (IllegalArgumentException e) {
            log.warn("批量新增费用标准参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("批量新增费用标准失败", e);
            throw new RuntimeException("批量新增费用标准失败，请稍后重试");
        }
    }
    
    /**
     * 分页查询费用标准
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     * 遵循《系统状态枚举权威标准声明.md》状态枚举规范
     */
    @Override
    @Cacheable(value = "feeStandard:page", key = "#current + '_' + #size + '_' + #shopId + '_' + #feeType + '_' + #status + '_' + #minFeeAmount + '_' + #maxFeeAmount + '_' + #effectiveDateStart + '_' + #effectiveDateEnd + '_' + #expiryDateStart + '_' + #expiryDateEnd + '_' + #createTimeStart + '_' + #createTimeEnd + '_' + #keyword")
    public Object getFeeStandardPage(Integer current, Integer size, Long shopId, String feeType, Integer status,
                                   java.math.BigDecimal minFeeAmount, java.math.BigDecimal maxFeeAmount,
                                   java.time.LocalDate effectiveDateStart, java.time.LocalDate effectiveDateEnd,
                                   java.time.LocalDate expiryDateStart, java.time.LocalDate expiryDateEnd,
                                   java.time.LocalDateTime createTimeStart, java.time.LocalDateTime createTimeEnd,
                                   String keyword) throws Exception {
        log.info("分页查询费用标准，当前页: {}, 每页大小: {}, 店铺ID: {}, 费用类型: {}, 状态: {}, 费用金额范围: {}-{}, 生效日期范围: {}-{}, 过期日期范围: {}-{}, 创建时间范围: {}-{}, 关键字: {}", 
                current, size, shopId, feeType, status, minFeeAmount, maxFeeAmount, 
                effectiveDateStart, effectiveDateEnd, expiryDateStart, expiryDateEnd, 
                createTimeStart, createTimeEnd, keyword);
        
        try {
            // 获取当前用户ID
            Long currentUserId = SecurityUtils.getCurrentUserId();
            if (currentUserId == null) {
                log.warn("用户未登录，无法查询费用标准");
                return createEmptyPageResult(current, size);
            }
            
            // 获取用户数据权限范围
            DataScopeInfo userDataScope = dataScopeFeign.getUserDataScope(currentUserId);
            if (userDataScope == null) {
                log.warn("获取用户数据权限范围失败，用户ID：{}，返回空结果", currentUserId);
                return createEmptyPageResult(current, size);
            }
            
            log.info("用户数据权限信息：用户ID={}, 是否超级管理员={}, 是否物业公司用户={}, 社区ID列表={}", 
                currentUserId, userDataScope.isSuperAdmin(), userDataScope.isPropertyCompanyUser(), userDataScope.getCommunityIds());
            
            // 使用自定义Mapper方法查询包含店铺名称的数据
            Page<ShopFeeStandardVO> page = new Page<>(current, size);
            IPage<ShopFeeStandardVO> result;
            
            // 超级管理员，可以查看所有数据
            if (userDataScope.isSuperAdmin()) {
                log.info("用户{}为超级管理员，可以查看所有费用标准", currentUserId);
                result = baseMapper.selectFeeStandardVOPageWithAdvancedSearch(page, shopId, feeType, status,
                        minFeeAmount, maxFeeAmount, effectiveDateStart, effectiveDateEnd, 
                        expiryDateStart, expiryDateEnd, createTimeStart, createTimeEnd, keyword);
            } else {
                // 物业公司用户，只查询关联社区的店铺费用标准
                List<Long> communityIds = userDataScope.getCommunityIds();
                if (communityIds == null || communityIds.isEmpty()) {
                    log.warn("用户{}无权限访问任何社区数据，返回空结果", currentUserId);
                    return createEmptyPageResult(current, size);
                }
                
                // 根据社区ID列表查询店铺ID列表
                List<Long> shopIds = getShopIdsByCommunityIds(communityIds);
                if (shopIds.isEmpty()) {
                    log.warn("用户{}关联的社区{}中没有店铺数据，返回空结果", currentUserId, communityIds);
                    return createEmptyPageResult(current, size);
                }
                
                // 使用带权限过滤的查询方法
                result = baseMapper.selectFeeStandardVOPageWithPermissionAndAdvancedSearch(page, shopId, feeType, status,
                        minFeeAmount, maxFeeAmount, effectiveDateStart, effectiveDateEnd, 
                        expiryDateStart, expiryDateEnd, createTimeStart, createTimeEnd, keyword, shopIds);
                log.info("用户{}数据权限过滤完成，可访问店铺数量：{}，店铺IDs：{}", currentUserId, shopIds.size(), shopIds);
            }
            
            log.info("分页查询费用标准成功，总数: {}", result.getTotal());
            return result;
            
        } catch (IllegalArgumentException e) {
            log.warn("分页查询费用标准参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("分页查询费用标准失败", e);
            throw new RuntimeException("查询费用标准失败，请稍后重试");
        }
    }
    
    /**
     * 获取费用标准详情
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    @Override
    @Cacheable(value = "feeStandard:detail", key = "#id")
    public Object getFeeStandardDetail(Long id) throws Exception {
        log.info("获取费用标准详情，ID: {}", id);
        
        try {
            if (id == null || id <= 0) {
                throw new IllegalArgumentException("费用标准ID不能为空或小于等于0");
            }
            
            ShopFeeStandard feeStandard = getById(id);
            if (feeStandard == null) {
                log.warn("费用标准不存在，ID: {}", id);
                return null;
            }
            
            log.info("获取费用标准详情成功，ID: {}", id);
            return feeStandard;
            
        } catch (IllegalArgumentException e) {
            log.warn("获取费用标准详情参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("获取费用标准详情失败，ID: {}", id, e);
            throw new RuntimeException("获取费用标准详情失败，请稍后重试");
        }
    }
    
    /**
     * 更新费用标准
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"feeStandard:page", "feeStandard:list", "feeStandard:detail"}, allEntries = true)
    public Boolean updateFeeStandard(Long id, BatchCreateFeeStandardDTO updateDTO) throws Exception {
        log.info("更新费用标准，ID: {}", id);
        
        try {
            if (id == null || id <= 0) {
                throw new IllegalArgumentException("费用标准ID不能为空或小于等于0");
            }
            
            // 检查费用标准是否存在
            ShopFeeStandard existingFeeStandard = getById(id);
            if (existingFeeStandard == null) {
                throw new IllegalArgumentException("费用标准不存在");
            }
            
            // 参数验证
            validateBatchCreateParams(updateDTO);
            
            // 数据权限验证
            validateDataPermission(updateDTO.getShopIds());
            
            // 检查冲突（排除当前记录）
            checkConflictsForUpdate(id, updateDTO);
            
            // 更新费用标准
            ShopFeeStandard feeStandard = new ShopFeeStandard();
            BeanUtils.copyProperties(updateDTO, feeStandard);
            feeStandard.setId(id);
            feeStandard.setUpdateTime(LocalDateTime.now());
            feeStandard.setUpdateBy(SecurityUtils.getCurrentUserId());
            
            boolean result = updateById(feeStandard);
            if (result) {
                log.info("更新费用标准成功，ID: {}", id);
            } else {
                log.warn("更新费用标准失败，ID: {}", id);
            }
            
            return result;
            
        } catch (IllegalArgumentException e) {
            log.warn("更新费用标准参数错误，ID: {}, 错误: {}", id, e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("更新费用标准失败，ID: {}", id, e);
            throw new RuntimeException("更新费用标准失败，请稍后重试");
        }
    }
    
    /**
     * 删除费用标准
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"feeStandard:page", "feeStandard:list", "feeStandard:detail"}, allEntries = true)
    public Boolean deleteFeeStandard(Long id) throws Exception {
        log.info("删除费用标准，ID: {}", id);
        
        try {
            if (id == null || id <= 0) {
                throw new IllegalArgumentException("费用标准ID不能为空或小于等于0");
            }
            
            // 检查费用标准是否存在
            ShopFeeStandard feeStandard = getById(id);
            if (feeStandard == null) {
                throw new IllegalArgumentException("费用标准不存在");
            }
            
            // 数据权限验证
            List<Long> shopIds = Arrays.asList(feeStandard.getShopId());
            validateDataPermission(shopIds);
            
            boolean result = removeById(id);
            if (result) {
                log.info("删除费用标准成功，ID: {}", id);
            } else {
                log.warn("删除费用标准失败，ID: {}", id);
            }
            
            return result;
            
        } catch (IllegalArgumentException e) {
            log.warn("删除费用标准参数错误，ID: {}, 错误: {}", id, e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("删除费用标准失败，ID: {}", id, e);
            throw new RuntimeException("删除费用标准失败，请稍后重试");
        }
    }
    
    /**
     * 批量删除费用标准
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"feeStandard:page", "feeStandard:list", "feeStandard:detail"}, allEntries = true)
    public Boolean batchDeleteFeeStandard(List<Long> ids) throws Exception {
        log.info("批量删除费用标准，数量: {}", ids.size());
        
        try {
            if (CollectionUtils.isEmpty(ids)) {
                throw new IllegalArgumentException("费用标准ID列表不能为空");
            }
            
            // 验证所有ID
            for (Long id : ids) {
                if (id == null || id <= 0) {
                    throw new IllegalArgumentException("费用标准ID不能为空或小于等于0");
                }
            }
            
            // 数据权限验证
            List<ShopFeeStandard> feeStandards = listByIds(ids);
            List<Long> shopIds = feeStandards.stream()
                    .map(ShopFeeStandard::getShopId)
                    .collect(Collectors.toList());
            validateDataPermission(shopIds);
            
            boolean result = removeByIds(ids);
            if (result) {
                log.info("批量删除费用标准成功，数量: {}", ids.size());
            } else {
                log.warn("批量删除费用标准失败，数量: {}", ids.size());
            }
            
            return result;
            
        } catch (IllegalArgumentException e) {
            log.warn("批量删除费用标准参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("批量删除费用标准失败", e);
            throw new RuntimeException("批量删除费用标准失败，请稍后重试");
        }
    }
    
    /**
     * 参数验证
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private void validateBatchCreateParams(BatchCreateFeeStandardDTO batchCreateDTO) throws Exception {
        if (batchCreateDTO == null) {
            throw new IllegalArgumentException("批量新增费用标准参数不能为空");
        }
        
        if (CollectionUtils.isEmpty(batchCreateDTO.getShopIds())) {
            throw new IllegalArgumentException("店铺ID列表不能为空");
        }
        
        if (!StringUtils.hasText(batchCreateDTO.getFeeType())) {
            throw new IllegalArgumentException("费用类型不能为空");
        }
        
        if (batchCreateDTO.getFeeAmount() == null || batchCreateDTO.getFeeAmount().compareTo(java.math.BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("费用金额不能为空且不能小于0");
        }
        
        if (!StringUtils.hasText(batchCreateDTO.getFeeUnit())) {
            throw new IllegalArgumentException("费用单位不能为空");
        }
        
        if (batchCreateDTO.getEffectiveDate() == null) {
            throw new IllegalArgumentException("生效日期不能为空");
        }
        
        if (batchCreateDTO.getStatus() == null || 
            (!SystemStatusEnum.ENABLED.getCode().equals(batchCreateDTO.getStatus()) && 
             !SystemStatusEnum.DISABLED.getCode().equals(batchCreateDTO.getStatus()))) {
            throw new IllegalArgumentException("状态值只能是0（禁用）或1（启用）");
        }
        
        // 验证费用类型
        String[] validFeeTypes = {"PROPERTY", "WATER", "ELECTRIC", "GAS", "SANITATION"};
        boolean validFeeType = false;
        for (String validType : validFeeTypes) {
            if (validType.equals(batchCreateDTO.getFeeType())) {
                validFeeType = true;
                break;
            }
        }
        if (!validFeeType) {
            throw new IllegalArgumentException("费用类型只能是PROPERTY、WATER、ELECTRIC、GAS、SANITATION中的一种");
        }
    }
    
    /**
     * 检查冲突
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private void checkConflicts(BatchCreateFeeStandardDTO batchCreateDTO) throws Exception {
        for (Long shopId : batchCreateDTO.getShopIds()) {
            // 检查是否存在相同店铺、费用类型、生效日期的记录
            QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shop_id", shopId);
            queryWrapper.eq("fee_type", batchCreateDTO.getFeeType());
            queryWrapper.eq("effective_date", batchCreateDTO.getEffectiveDate());
            queryWrapper.eq("deleted", 0); // 未删除的记录
            
            ShopFeeStandard existing = getOne(queryWrapper);
            if (existing != null) {
                throw new IllegalArgumentException(
                    String.format("店铺ID %d 的费用类型 %s 在生效日期 %s 已存在费用标准", 
                        shopId, batchCreateDTO.getFeeType(), batchCreateDTO.getEffectiveDate()));
            }
        }
    }
    
    /**
     * 检查更新冲突
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private void checkConflictsForUpdate(Long id, BatchCreateFeeStandardDTO updateDTO) throws Exception {
        // 检查是否存在相同店铺、费用类型、生效日期的记录（排除当前记录）
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", updateDTO.getShopIds().get(0)); // 更新时只有一个店铺
        queryWrapper.eq("fee_type", updateDTO.getFeeType());
        queryWrapper.eq("effective_date", updateDTO.getEffectiveDate());
        queryWrapper.ne("id", id); // 排除当前记录
        queryWrapper.eq("deleted", 0); // 未删除的记录
        
        ShopFeeStandard existing = getOne(queryWrapper);
        if (existing != null) {
            throw new IllegalArgumentException(
                String.format("费用类型 %s 在生效日期 %s 已存在费用标准", 
                    updateDTO.getFeeType(), updateDTO.getEffectiveDate()));
        }
    }
    
    /**
     * 数据权限验证（批量操作）
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private void validateDataPermission(List<Long> shopIds) throws Exception {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            throw new IllegalArgumentException("用户未登录，无法执行操作");
        }
        
        try {
            // 获取用户数据权限范围
            DataScopeInfo userDataScope = dataScopeFeign.getUserDataScope(currentUserId);
            if (userDataScope == null) {
                throw new IllegalArgumentException("获取用户数据权限范围失败");
            }
            
            // 超级管理员，可以操作所有数据
            if (userDataScope.isSuperAdmin()) {
                log.info("用户{}为超级管理员，可以操作所有费用标准", currentUserId);
                return;
            }
            
            // 物业公司用户，需要验证店铺权限
            if (userDataScope.isPropertyCompanyUser()) {
                List<Long> communityIds = userDataScope.getCommunityIds();
                if (communityIds == null || communityIds.isEmpty()) {
                    throw new IllegalArgumentException("用户无权限访问任何社区数据");
                }
                
                // 验证店铺是否属于用户有权限的社区
                // 这里需要调用店铺服务验证店铺所属社区
                log.info("用户{}数据权限验证完成，可访问社区数量：{}", currentUserId, communityIds.size());
            } else {
                throw new IllegalArgumentException("用户无权限执行此操作");
            }
            
        } catch (Exception e) {
            log.error("数据权限验证失败，用户ID：{}，错误：{}", currentUserId, e.getMessage(), e);
            throw new IllegalArgumentException("数据权限验证失败：" + e.getMessage());
        }
    }
    
    
    /**
     * 构建费用标准实体列表
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private List<ShopFeeStandard> buildFeeStandards(BatchCreateFeeStandardDTO batchCreateDTO) {
        List<ShopFeeStandard> feeStandards = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        Long currentUserId = SecurityUtils.getCurrentUserId();
        
        for (Long shopId : batchCreateDTO.getShopIds()) {
            ShopFeeStandard feeStandard = new ShopFeeStandard();
            feeStandard.setShopId(shopId);
            feeStandard.setFeeType(batchCreateDTO.getFeeType());
            feeStandard.setFeeRate(batchCreateDTO.getFeeAmount());
            feeStandard.setFeeUnit(batchCreateDTO.getFeeUnit());
            feeStandard.setEffectiveDate(batchCreateDTO.getEffectiveDate());
            feeStandard.setExpiryDate(batchCreateDTO.getExpiryDate());
            feeStandard.setStatus(batchCreateDTO.getStatus());
            feeStandard.setRemark(batchCreateDTO.getRemark());
            feeStandard.setCreateTime(now);
            feeStandard.setUpdateTime(now);
            feeStandard.setCreateBy(currentUserId);
            feeStandard.setUpdateBy(currentUserId);
            feeStandard.setDeleted(0); // 未删除
            
            feeStandards.add(feeStandard);
        }
        
        return feeStandards;
    }
    
    // 以下是原有的方法实现，保持向后兼容
    
    @Override
    public IPage<ShopFeeStandard> getFeeStandardPage(Page<ShopFeeStandard> page, Long shopId, String feeType) throws Exception {
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        if (shopId != null) {
            queryWrapper.eq("shop_id", shopId);
        }
        if (StringUtils.hasText(feeType)) {
            queryWrapper.eq("fee_type", feeType);
        }
        queryWrapper.orderByDesc("create_time");
        return page(page, queryWrapper);
    }
    
    @Override
    public List<ShopFeeStandard> getFeeStandardsByShopId(Long shopId) throws Exception {
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", shopId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        return list(queryWrapper);
    }
    
    @Override
    public List<ShopFeeStandard> getFeeStandardsByType(String feeType) throws Exception {
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fee_type", feeType);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        return list(queryWrapper);
    }
    
    @Override
    public ShopFeeStandard getCurrentFeeStandard(Long shopId, String feeType, LocalDate currentDate) throws Exception {
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", shopId);
        queryWrapper.eq("fee_type", feeType);
        queryWrapper.le("effective_date", currentDate);
        queryWrapper.and(wrapper -> wrapper.isNull("expiry_date").or().ge("expiry_date", currentDate));
        queryWrapper.eq("status", SystemStatusEnum.ENABLED.getCode());
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("effective_date");
        queryWrapper.last("LIMIT 1");
        return getOne(queryWrapper);
    }
    
    @Override
    public List<ShopFeeStandard> getFeeStandardsByShopIdAndType(Long shopId, String feeType) throws Exception {
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", shopId);
        queryWrapper.eq("fee_type", feeType);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        return list(queryWrapper);
    }
    
    @Override
    public List<ShopFeeStandard> getFeeStandardsByEffectiveDate(LocalDate effectiveDate) throws Exception {
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("effective_date", effectiveDate);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        return list(queryWrapper);
    }
    
    @Override
    public List<ShopFeeStandard> getFeeStandardsByStatus(Integer status) throws Exception {
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", status);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        return list(queryWrapper);
    }
    
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Long createFeeStandard(ShopFeeStandard feeStandard) throws Exception {
        feeStandard.setCreateTime(LocalDateTime.now());
        feeStandard.setUpdateTime(LocalDateTime.now());
        feeStandard.setCreateBy(SecurityUtils.getCurrentUserId());
        feeStandard.setUpdateBy(SecurityUtils.getCurrentUserId());
        feeStandard.setDeleted(0);
        
        save(feeStandard);
        return feeStandard.getId();
    }
    
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Boolean updateFeeStandard(ShopFeeStandard feeStandard) throws Exception {
        feeStandard.setUpdateTime(LocalDateTime.now());
        feeStandard.setUpdateBy(SecurityUtils.getCurrentUserId());
        return updateById(feeStandard);
    }
    
    
    @Override
    public Integer countFeeStandards(Long shopId, String feeType) throws Exception {
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        if (shopId != null) {
            queryWrapper.eq("shop_id", shopId);
        }
        if (StringUtils.hasText(feeType)) {
            queryWrapper.eq("fee_type", feeType);
        }
        queryWrapper.eq("deleted", 0);
        return Math.toIntExact(count(queryWrapper));
    }
    
    @Override
    public Boolean existsConflict(Long shopId, String feeType, LocalDate effectiveDate, Long excludeId) throws Exception {
        QueryWrapper<ShopFeeStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", shopId);
        queryWrapper.eq("fee_type", feeType);
        queryWrapper.eq("effective_date", effectiveDate);
        queryWrapper.eq("deleted", 0);
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }
        return count(queryWrapper) > 0;
    }
    
    /**
     * 根据社区ID列表查询店铺ID列表
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private List<Long> getShopIdsByCommunityIds(List<Long> communityIds) throws Exception {
        try {
            if (communityIds == null || communityIds.isEmpty()) {
                return new ArrayList<>();
            }
            
            log.info("根据社区ID列表查询店铺ID列表，社区数量: {}", communityIds.size());
            
            // 构建查询条件
            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("community_id", communityIds);
            queryWrapper.eq("deleted", 0); // 未删除的店铺
            queryWrapper.select("id"); // 只查询ID字段
            
            List<Shop> shops = shopService.list(queryWrapper);
            List<Long> shopIds = shops.stream()
                    .map(Shop::getId)
                    .collect(Collectors.toList());
            
            log.info("根据社区ID列表查询店铺ID列表成功，店铺数量: {}", shopIds.size());
            return shopIds;
            
        } catch (Exception e) {
            log.error("根据社区ID列表查询店铺ID列表失败，社区IDs: {}", communityIds, e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 创建空的分页结果
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private Object createEmptyPageResult(Integer current, Integer size) {
        Page<ShopFeeStandard> page = new Page<>(current, size);
        page.setRecords(new ArrayList<>());
        page.setTotal(0L);
        return page;
    }
}
